// pages/pay/pay.js
var Pingpp = require("../../utils/pingpp.js");
const Format = require("../../utils/time.js");
var app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        totalcount: 0,
        totalmey: 0,
        payarr: [],
        discount: 0,
        isDiscount: false,
        isOendis: false,
        codes: "",
        isChinese: wx.getStorageSync("isChinese"),
        paying: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let newcount = this.data.totalcount,
            that = this,
            newmey = this.data.totalmey;
        that.setData({
            isChinese: wx.getStorageSync("isChinese")
        });
        wx.setNavigationBarTitle({
            title: that.data.isChinese ? "付款" : "Check Out"
        });
        that.setData({
            items: app.globalData.activityDetails,
            eventId: app.globalData.activityDetails.eventId,
            id: app.globalData.activityDetails.id,
            eventType: app.globalData.activityDetails.eventType,
            venueName: app.globalData.venueName,
            eventName: app.globalData.eventName,
            cityName: app.globalData.cityName,
            eventLocation: app.globalData.location,
            isType: options.isType
                // actuallyPaid: that.data.items.unitPrice * that.data.items.count
        });
        app.getApi.getProducts("POST", {
                method: "opg.default.nameandemail.find",
                unionId: app.globalData.unionId
            })
            .then(data => {
                that.setData({
                    formDatas: data.data
                });
            });
        var payarr;
        if (options.isType == 0) {
            payarr = wx.getStorageSync("payarr");
            for (let i = 0; i < payarr.length; i++) {
                newcount = newcount + payarr[i].count;
                newmey = newmey + payarr[i].count * payarr[i].unitPrice;
            }
        } else {
            payarr = [];
            payarr.push(JSON.parse(options.location));
            console.log(payarr, "payarr")
            newcount = newcount + payarr[0].count;
            newmey = newmey + payarr[0].count * payarr[0].deposit;
        }
        this.setData({
            payarr: payarr,
            actuallyPaid: newmey,
            totalcount: newcount,
            totalmey: newmey
        });
    },
    onShow() {
        this.setData({ paying: false })
    },
    cartItem() {
        let cartItem = this.data.payarr,
            cartItemList = [];
        if (this.data.isType == 0) {
            for (let i = 0; i < cartItem.length; i++) {
                let newObj = {};
                if (cartItem[i].count > 0) {
                    newObj.count = cartItem[i].count;
                    newObj.itemId = cartItem[i].id;
                    newObj.salesPrice = cartItem[i].unitPrice;
                    newObj.goodsTypeEnum = "EVENT_TICKET";
                    cartItemList.push(newObj);
                }
            }
        } else {
            for (let i = 0; i < cartItem.length; i++) {
                let newObj = {};
                if (cartItem[i].count > 0) {
                    newObj.count = cartItem[i].count;
                    newObj.itemId = cartItem[i].id;
                    newObj.salesPrice = cartItem[i].deposit;
                    newObj.goodsTypeEnum = "EVENT_TABLE";
                    cartItemList.push(newObj);
                }
            }
        }
        return cartItemList;
    },
    timestamp: function() {
        var timestamp = Date.parse(new Date());
        var closeTime = parseInt(this.data.items.closeTime)
        if (closeTime - timestamp < 0) {
            wx.showModal({
                content: this.data.isChinese ? '线上售票已截止，请客官到活动现场购买！' : "Online ticket sold out，you can purchase at the event site.",
                showCancel: false,
                success: function(res) {
                    if (res.confirm) {
                        return;
                    }
                }
            })

        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */

    code() {

        if (this.data.uncheckedCode == "") {
            wx.showToast({
                title: "未输入优惠码",
                icon: "loading",
                duration: 2000
            });
            return;
        }
        wx.showLoading({
            title: ""
        });
        var that = this;
        app.getApi.getProducts("POST", {
                //验证优惠券是否可用
                cartItemList: JSON.stringify(that.cartItem()),
                discountNumber: that.data.uncheckedCode,
                eventId: that.data.eventId,
                method: "opg.benefit.checkout"
            })
            .then(data => {
                if (data.data.discountNumberIsActive) {
                    //可用操作
                    that.setData({
                        isOendis: true,
                        isDiscount: true,
                        codes: that.data.uncheckedCode,
                        discount: data.data.discountAmount,
                        actuallyPaid: parseFloat(
                            that.data.totalmey - data.data.discountAmount
                        ).toFixed(2)
                    });
                } else {
                    that.setData({
                        isOendis: true,
                        isDiscount: false,
                        codes: "",
                        actuallyPaid: parseFloat(that.data.totalmey).toFixed(2)
                    });
                }
                wx.hideLoading();
            });
    },
    delate() {
        this.setData({
            actuallyPaid: parseFloat(this.data.totalmey).toFixed(2),
            codesL: "",
            codes: "",
            isOendis: false,
            isDiscount: false,
            discount: 0
        });
    },
    inputcode(e) {
        this.setData({
            uncheckedCode: e.detail.value
        });
    },
    jian(e) {
        let index = e.currentTarget.dataset.index,
            price = e.currentTarget.dataset.price,
            ticket = this.data.payarr;

        if (ticket[index].count <= 1) {
            return;
        }
        ticket[index].count--;
        this.setData({
            payarr: ticket,
            codesL: "",
            codes: "", //对数量操作优惠券重置
            isOendis: false,
            isDiscount: false,
            discount: 0
        });
        // this.delate();
        this.total(1, price);
    },
    jia(e) {
        let index = e.currentTarget.dataset.index,
            price = e.currentTarget.dataset.price,
            ticket = this.data.payarr;

        if (ticket[index].count >= ticket[index].balance) {
            wx.showModal({
                title: this.data.isChinese ? "提示" : "Prompt",
                showCancel: false,
                content: this.data.isChinese ? '没有更多票啦!' : 'No more!'
            })
            return;
        }
        // console.log(ticket)
        if ((ticket[index].count >= ticket[index].ticketOneCount && ticket[index].ticketOneCount > 0) || (ticket[index].count >= ticket[index].tableOneCount && ticket[index].tableOneCount > 0)) {
            // wx.showModal({
            //     title: this.data.isChinese ? "提示" : "Prompt",
            //     showCancel: false,
            //     content: this.data.isChinese ? '单张限购' + ticket[index].ticketOneCount || ticket[index].tableOneCount + '张' : 'Limit' + ticket[index].ticketOneCount || ticket[index].tableOneCount + 'per order'
            // })
            return;
        }
        ticket[index].count++;
        this.setData({
            payarr: ticket,
            codesL: "",
            codes: "", //对数量操作优惠券重置
            isOendis: false,
            isDiscount: false,
            discount: 0
        });
        // this.delate();
        this.total(0, price);
    },
    total(types, price) {
        let count = this.data.totalcount,
            totalprice = this.data.totalmey;
        if (types == 0) {
            count++;
            totalprice = (Number(price) + Number(totalprice)).toFixed(2);
        } else {
            count--;
            totalprice = (totalprice - price).toFixed(2);
        }
        // totalprice = totalprice
        this.setData({
            totalcount: count,
            totalmey: totalprice,
            actuallyPaid: totalprice
        });
    },
    select() {},
    formSubmit: function(e) {
        if (this.data.paying) {
            return
        }
        this.setData({ paying: true })
            //支付
        this.timestamp()
        var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        var arr = [];
        for (var i in e.detail.value) {
            if (e.detail.value[i] == "") {
                wx.showModal({
                    title: this.data.isChinese ? "提示" : "Prompt",
                    content: this.data.isChinese ? "昵称不能为空" : "Name Required",
                    showCancel: false
                });
                return;
            }
        }
        if (!myreg.test(e.detail.value.email)) {
            wx.showModal({
                title: this.data.isChinese ? "提示" : "Prompt",
                content: this.data.isChinese ? "邮箱格式不正确" : "Email format is wrong",
                showCancel: false
            });
            return;
        }

        wx.showLoading({
            title: ""
        });
        var that = this,
            formData = {},
            activity = that.data.items;
        let cartItem = this.data.payarr,
            cartItemList = [],
            newCount = 0;
        for (let i = 0; i < cartItem.length; i++) {
            //生成订单的参数（票的信息）
            var newObj = {};
            if (cartItem[i].count > 0) {
                newObj.format = "json";
                newObj.locale = "zh_CN";
                newObj.objectId = cartItem[i].id;
                newObj.objectName = cartItem[i].name;
                if (that.data.isType == 0) {
                    newObj.objectType = "EVENT_TICKET";
                } else {
                    newObj.objectType = "EVENT_TABLE";
                }
                newCount += cartItem[i].count
                newObj.quantity = cartItem[i].count;
                newObj.sign_method = "md5";
                newObj.taxRate = 0;
                newObj.timestamp = Date.parse(new Date());
                newObj.unitPrice = cartItem[i].unitPrice;
                newObj.v = "1.0";
                if (that.data.isType == 1) {
                    newObj.unitPrice = cartItem[i].deposit;
                }
                cartItemList.push(newObj);
            }
        }
        app.getApi.getProducts("POST", {
                // 提交订单
                eventId: activity.eventId,
                eventName: activity.eventName,
                isFromPromote: 1,
                objectId: activity.id,
                objectType: activity.eventType,
                orderLineList: JSON.stringify(cartItemList),
                paidAmount: that.data.actuallyPaid,
                promoteUnionId: activity.promoteUnionId,
                promoteUnionName: activity.promoteUnionName,
                totalAmount: that.data.totalmey,
                promotePartyId: activity.id,
                unionId: app.globalData.unionId,
                unionMail: e.detail.value.email,
                unionName: e.detail.value.lastName,
                // memberId: "857573744049524736",
                // userId: "857573744049524736",
                method: "opg.orderHead.create"
            })
            .then(datas => {
                //   setTimeout(function () {
                // that.setData({ paying: false })
                //   }, 2000)

                if (cartItem[0].currencyCode == "RMB") {
                    //人民币支付
                    app.getApi
                        .getProducts("POST", {
                            // 获取create用于支付
                            method: "opg.mobile.charge.create",
                            orderId: datas.data.id,
                            openId: app.globalData.openid,
                            currency: "cny",
                            channel: "wx_lite",
                            amount: that.data.actuallyPaid,
                            unionMail: e.detail.value.email,
                            discountNumber: that.data.codes,
                            orderNo: datas.data.orderNo
                        })
                        .then(data => {
                            if (data.data.errors.length == 0) {
                                wx.hideLoading();
                                Pingpp.createPayment(data.data.charge, function(result, err) {
                                    that.setData({ paying: false })
                                        //调起ping+支付
                                    if (result == "success") {

                                        app.globalData.newCount = newCount //新增票券的数量
                                        wx.setTabBarBadge({
                                            index: 1,
                                            text: app.globalData.newCount
                                        })
                                        wx.reLaunch({
                                            url: '../paySucc/paySucc',
                                            success: function(res) {},
                                            fail: function(res) {},
                                            complete: function(res) {},
                                        })
                                    } else if (result == "fail") {
                                        wx.showModal({
                                            title: that.data.isChinese ? "提示" : "Prompt",
                                            showCancel: false,
                                            content: that.data.isChinese ?
                                                "支付失败,请重新尝试" : "Payment failure, please try again"
                                        });
                                        // charge 不正确或者微信公众账号支付失败时会在此处返回
                                    } else if (result == "cancel") {
                                        // 微信公众账号支付取消支付
                                        wx.showModal({
                                            title: that.data.isChinese ? "提示" : "Prompt",
                                            showCancel: false,
                                            content: that.data.isChinese ?
                                                "支付失败,请重新尝试" : "Payment failure, please try again"
                                        });
                                    }
                                });
                            } else {
                                wx.hideLoading();
                                that.setData({ paying: false })
                                wx.showModal({
                                    title: "提示",
                                    showCancel: false,
                                    content: data.data.firstErrorMessage
                                });
                            }
                        });
                } else {
                    wx.hideLoading();
                    // that.setData({ paying: false })
                    wx.navigateTo({
                        url: '../paydollar/paydollar?res_data=' + JSON.stringify(datas.data) + '&totalmey=' + that.data.actuallyPaid + '&=unionMail' + e.detail.value.email + "&newCount=" + newCount + "&codes=" + that.data.codes
                    })
                }
            }).catch(datas => {
                wx.hideLoading();
                that.setData({ paying: false })
            });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {
        // wx.clearStorageSync();
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        // wx.clearStorageSync();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {}
});